import { rsaEncrypt, setSymmKeyIndex, setPublicKey, generateAesKey } from '@/libs/util'
import { login, getPublicKey } from '../../api/userService'

export default {
  state: {
    user: {},
    apiGate: '',
    version: ''
  },
  mutations: {
    setUser (state, user) {
      state.userName = user
    },
    setApiGate (state, apiGate) {
      state.apiGate = apiGate
    },
    setVersion (state, Version) {
      state.userId = Version
    }
  },
  actions: {
    // 登录
    handleLogin ({ commit }, {userName, password}) {
      userName = userName.trim()
      var token
      console.debug('handleLogin登陆:', userName, password)
      return new Promise((resolve, reject) => {
        getPublicKey().then(res => {
          setPublicKey(res.publicKey)
          commit('setApiGate', res.apiGate)
          commit('setVersion', res.version)
          token = {
            client: 'web',
            data: rsaEncrypt({
              name: userName,
              password: password,
              symmkey: generateAesKey()
            }, res.publicKey)
          }
          return login(token)
        }).then(data => {
          if (resolve && data.status === 'success') {
            commit('setUser', data)
            setSymmKeyIndex(data.userId)
            resolve(data)
          } else reject(data.status)
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 退出登录
    handleLogOut ({ state, commit }) {
      return new Promise((resolve, reject) => {
        setPublicKey('')
        commit('setApiGate', '')
        commit('setVersion', '')
        commit('setUser', {})
        setSymmKeyIndex(0)
        resolve()
      })
    }
    // // 获取用户相关信息
    // getUserInfo ({ state, commit }) {
    //   return new Promise((resolve, reject) => {
    //     getUserInfo(state.token).then(res => {
    //       const data = res.data
    //       commit('setAvator', data.avator)
    //       commit('setUserName', data.user_name)
    //       commit('setUserId', data.user_id)
    //       commit('setAccess', data.access)
    //       resolve(data)
    //     }).catch(err => {
    //       reject(err)
    //     })
    //   })
    // }
  }
}
